package com.tao.widget

import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.ActionMenuView
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.get
import com.tao.R

/**
 * 自定义标题栏
 * toolbar中使用到了R.attr.toolbarStyle如果构造器使用this连环调用，toolbarStyle将不会加载
 */
class TitleBar : Toolbar {

    private lateinit var titleView: TextView
    private lateinit var centerText: String

    constructor(context: Context) : super(context) {
        init(null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        attrs?.run {
            val typedArray = context.obtainStyledAttributes(this, R.styleable.TitleBar)
            centerText = typedArray.getString(R.styleable.TitleBar_centerText) ?: ""
            typedArray.recycle();
        }
        addTitle()
    }

    /**
     * 添加居中的标题
     */
    private fun addTitle() {
        titleView = TextView(context)
        titleView.text = centerText
        titleView.setTextColor(ContextCompat.getColor(context, android.R.color.black))
        titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18F)
        titleView.setSingleLine()
        titleView.gravity = Gravity.CENTER
        addView(
            titleView, LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.MATCH_PARENT,
                Gravity.CENTER
            )
        )
        setContentInsetsRelative(0, 0)
    }

    /**
     * 设置标题
     */
    override fun setTitle(resId: Int) {
        setTitle(context.getText(resId))
    }

    override fun setTitle(title: CharSequence) {
        titleView.text = title
    }

    /**
     * 创建menu
     * @param banToast 是否长按显示
     */
    fun inflateMenu(resId: Int, banToast: Boolean = false) {
        super.inflateMenu(resId)
        // 隐藏
        if (banToast) {
            banToast()
        }
    }

    /**
     * 屏蔽menuItem长按toast
     * menu add或者remove后都需要手动调用，屏蔽toast
     */
    fun banToast() {
        for (i in childCount -1 downTo 0) {
            // 从后往前找，ActionMenuView一般是最后一个
            val view = get(i)
            if (view is ActionMenuView) {
                val menuView = view as ActionMenuView
                for (j in 0 until menuView.childCount) {
                    menuView.get(j).setOnLongClickListener { true }
                }
                break
            }
        }
    }
}